<?php 

class Carts extends AppController{
	public function __construct(){
		parent::__construct();
	}
	public function index(){

	}
	public function view($id=NULL){
		$cart = $this->cart->contents();
		$data = array();

		foreach($cart as $v):
			$product = $this->getEM()->getRepository('\Entity\ShProduct')->findOneById($v['id']);
			if(empty($product))
				continue;

			$data[] = array(
				'id' => $product->getId(),
				'name' => $product->getName(),
				'qty' => $v['qty'],
				'price' => $v['price'],
				'options' => $v['options'],
				'subtotal' => $v['subtotal']
			);
		endforeach;

		$this->data['hide_category'] = true;
		$this->data['cart'] = $data;
		$this->render('cart/view');
	}

	public function checkout(){
		if(!$this->session->userdata('uid'))
			redirect('/user/login');

		$cart = $this->cart->contents();
		if(empty($cart))
			redirect('/');

		// $this->getEM()->getRepository('\Entity\ShCart')->checkout(false, false, false);exit;
		$this->validation();
		if($this->input->post() && $this->form_validation->run('checkout')):
			try {
				$this->getEM()->getRepository('\Entity\ShCart')->checkOut(
					$this->input, $cart,
					$this->session->userdata('uid'),
					$this->cart->total()
				);
				$this->cart->destroy();
				redirect('/');
			} catch (\Exception $e){
				$mess = $e->getMessage();
				var_dump($mess);
			}
		endif;

		$this->data['hide_category'] = true;
		$this->render('/cart/checkout');
	}
	
	public function add_to_cart($id = null){
		if(empty($id))
			redirect('/');
			
		$ajax = $this->isAjax();
		
		if($this->cart->total_items() > 10 || count($this->cart->contents())>5):
			if($ajax)
				exit(json_encode(array('type'=>'0','mess' => 'Số lượng sản phẩm trong giỏ hàng đạt ngưỡng, xin vui lòng thanh toán trước')));
			else
				redirect('/');
		endif;
			
		$data = array(
				'id' => $id,
				'name' => 'product id'.$id,
				'qty' => $this->input->post('qty'),
				'price' => $this->input->post('price'),
				'options' => array(
					'size' => $this->input->post('size'),
					'color' => $this->input->post('color')
				),
			);
			
		if(empty($data['qty']) || $data['qty'] >5 || $data['qty']<=0):
			if($ajax)
				exit(json_encode(array('type'=>'0','mess' => 'Số lượng sản phẩm không cho phép')));
			else
				redirect('/');
		endif;
		
		$product = $this->getEM()->getRepository('\Entity\ShProduct')->findProductForCart($id, $data['qty']);
		if(empty($product)):
			if($ajax)
				exit(json_encode(array('type'=>'0','mess' => 'Không có sản phẩm này')));
			else
				redirect('/');
		endif;
		
		$user = $this->session->userdata('uid');
		if(empty($user)):
			if($ajax)
				exit(json_encode(array('type'=>'0','mess' => 'Xin hãy đăng nhập trước')));
			else
				redirect('/user/login');
		endif;
			
		$cart_total = $this->getEM()->getRepository('\Entity\ShCart')->countCart($user);
		
		if($cart_total < 3):
			//checking product's image	
			$img = $product->getImage();
			if(empty($img)):
				$data['options']['img'] = 'notfound.jpg';
				$data['options']['hasImage'] = false;
			else:
				$data['options']['img'] = $img->getName();
				$data['options']['hasImage'] = true;
			endif;

 			if(!empty($data['options']['color']) || !empty($data['options']['size'])):
				$extends = $this->getEM()->getRepository('\Entity\ShProduct')->findWithExtension($id, $data);
				if(!empty($extends)):

					foreach($extends as $v):
						if(!empty($data['options']['color']) && $v['id'] == $data['options']['color'])
							$data['options']['color_name'] = $v['name'];

						if(!empty($data['options']['size']) && $v['id'] == $data['options']['size'])
							$data['options']['size_name'] = $v['val'];
					endforeach;
					$add = $this->cart->insert($data);
				endif;
			else:
				$extends = $this->getEM()->getRepository('\Entity\ShProduct')->findExtension($id);
				if(empty($extends['size']) && empty($extends['color']))
					$add = $this->cart->insert($data);
			endif;
			
			if(!empty($add)):
				if($ajax)
					exit(json_encode(array('type'=>'1','mess' => 'Thêm sản phẩm thành công')));
				else
					redirect('/carts/detail');
			else:
				if($ajax)
					exit(json_encode(array('type'=>'0','mess' => 'Không có sản phẩm nào phù hợp')));
				else
					redirect('/');
			endif;
		else:
			if($ajax)
				exit(json_encode(array('type'=>'0','mess' => 'Số lượng đơn hàng cũ của bạn qúa nhiều, xin đợi')));
			else
				redirect('/');
		endif;
		var_dump($product);
		
	}
	public function admin_index($sortBy='id',$sortOrder = 'desc'){
		$pag = array(
			'uri_segment'=>6,
			'sort'=>true,
			'per_page'=>10,
			'sortList'=>array('stt'=>'id','Tên Khách Hàng'=>'cusname','Email'=>'cusemail','Địa Chỉ'=>'cusaddress','Số Đt'=>'cusphone','Ngày Mua'=>'daterequest','Ngày Gởi'=>'datedelivery','Tình trạng'=>'status','Tổng tiền'=>'totalmoney'),
			'base_url'=>'/admin/cart/index',
			'sortBy'=>$sortBy,
			'sortOrder'=>$sortOrder
			);
		$pag = $this->paginate($pag);
		$pag['total_rows'] = $this->getEM()->getRepository('Entity\ShCart')->total_rows($pag);
		$this->pagination->initialize($pag);
		$this->data['pagination_link'] = $this->pagination->create_links();
		$this->data['carts'] = $this->getEM()->getRepository('\Entity\ShCart')->backendPaginate($pag);
		$this->render('cart/admin_index');
	}
	public function mod_index($sortBy='id',$sortOrder = 'desc'){
		$pag = array(
			'uri_segment'=>6,
			'sort'=>true,
			'per_page'=>10,
			'sortList'=>array('stt'=>'id','Tên Khách Hàng'=>'cusname','Email'=>'cusemail','Địa Chỉ'=>'cusaddress','Số Đt'=>'cusphone','Ngày Mua'=>'daterequest','Ngày Gởi'=>'datedelivery','Tình trạng'=>'status','Tổng tiền'=>'totalmoney'),
			'base_url'=>'/admin/cart/index',
			'sortBy'=>$sortBy,
			'sortOrder'=>$sortOrder
			);
		$pag = $this->paginate($pag);
		$pag['total_rows'] = $this->getEM()->getRepository('Entity\ShCart')->total_rows($pag);
		$this->pagination->initialize($pag);
		$this->data['pagination_link'] = $this->pagination->create_links();
		$this->data['carts'] = $this->getEM()->getRepository('\Entity\ShCart')->backendPaginate($pag);
		$this->render('cart/mod_index');
	}
	public function admin_add(){
		$this->carts_add();
		$this->data['breadcrumb']=array(
			'Giỏ Hàng' =>base_url('/admin/carts'),
			'Thêm Giỏ Hàng' => NULL
			);
		$this->render('cart/admin_add',
			array('jquery.sceditor.bbcode.min','language/vi','sceditor','thumbnail-module'),
			array('default.min','tabs')
			);
	}
	public function mod_add(){
		$this->validation();

		if($this->input->post() /*&& $this->form_validation->run('carts')*/):
			if($this->getEM()->getRepository('Entity\ShCart')->addCarts($this->input)):
				$this->log(7,array($this->data['user']));
				$this->session->set_flashdata('success','Thêm Giỏ Hàng Thành Công');
			redirect('/admin/carts');
			else:
				$this->data['flash'] = array('error'=>'Lỗi sql, Thử lại');
			endif;
		endif;
		$this->data['breadcrumb']=array(
			'Giỏ Hàng' =>base_url('/admin/carts'),
			'Thêm Giỏ Hàng' => NULL
			);
		$this->render('cart/admin_add',
			array('jquery.sceditor.bbcode.min','language/vi','sceditor','thumbnail-module'),
			array('default.min','tabs')
			);
	}
	public function admin_delete($id = null){
		if(empty($id))
			redirect('/admin/carts/'.$id);
			
		$cart = $this->getEM()->getRepository('Entity\ShCart')->findOneById($id);
		if(empty($cart))
			redirect('/admin/carts/'.$id);
		
		try {
			$cart->setStatus(-1);
			$this->getEM()->persist($cart);
			$this->getEM()->flush();
			
			$this->session->set_flashdata('success', 'Chỉnh sửa đơn hàng thành công');
			$this->log(2,array($this->data['user']));
		} catch(Exception $e){
			$this->session->set_flashdata('success', $e->getMessage());
		}
		redirect('/admin/carts');

	}
	
	public function admin_edit($id = null){
		if(empty($id))
			redirect('/admin/carts/'.$id);
			
		$cart = $this->getEM()->getRepository('Entity\ShCart')->findOneById($id);
		if(empty($cart))
			redirect('/admin/carts/'.$id);
			
		$this->data['cart'] = $cart;
		$this->data['cart_detail'] = $this->getEM()->getRepository('Entity\ShCartdetail')->findByshCart($cart);
		$this->data['cart_status'] = $this->getEM()->getRepository('Entity\ShExtension')->findBy(array(
				'type' => 1,
				'status' => 1
			));

		if($this->input->post()):
			// var_dump($this->input->post());exit;
			$data = array(
				'status' => $this->input->post('status'),
				'id' => $id
			);
			$list_p = $this->input->post('product');
			foreach($list_p as $v):
				$temp = explode(';', $v);

				$p_id = explode('=', $temp[0]);
				$qty = $this->input->post('product_'.$p_id[1]);
				$data['product'][$p_id[1]] = array(
					'p_id' => $p_id[1],
					'qty' => $qty
				);
			endforeach;

			$this->getEM()->getRepository('Entity\ShCart')->editCart($data, $cart);			
			$this->log(13,array(
				$this->session->userdata('uid'),
				$this->session->userdata('username'),
				$id
			));
			redirect('/admin/carts/index');
		endif;

		$this->render('cart/admin_edit');
	}
	public function mod_edit($id = NULL){
		if(empty($id))
			redirect('/admin/carts/'.$id);
			
		$cart = $this->getEM()->getRepository('Entity\ShCart')->findOneById($id);
		if(empty($cart))
			redirect('/admin/carts/'.$id);
			
		$this->data['cart'] = $cart;
		$this->data['cart_detail'] = $this->getEM()->getRepository('Entity\ShCartdetail')->findByshCart($cart);
		$this->data['cart_status'] = $this->getEM()->getRepository('Entity\ShExtension')->findBy(array(
				'type' => 1,
				'status' => 1
			));
		$this->render('cart/admin_edit',
			array(),
			array('carts')
		);
		$user = $this->session->userdata('username');
		$this->log(13,array($user));
	}
	public function admin_search(){
		$val = $this->input->post('value');
		$product = $this->getEM()->getRepository('\Entity\ShProduct')->admin_search_for_cart($val);
		if(!	empty($product))
			$product = $this->getEM()->getRepository('\Entity\ShProduct')->getExtension($product);
		
		echo json_encode($product);
		
		exit;
	}
	public function mod_search(){
		$val = $this->input->post('value');
		$product = $this->getEM()->getRepository('\Entity\ShProduct')->admin_search_for_cart($val);
		if(!	empty($product))
			$product = $this->getEM()->getRepository('\Entity\ShProduct')->getExtension($product);
		
		echo json_encode($product);
		
		exit;
	}
	private function carts_add(){
		$this->validation();

		if($this->input->post() /*&& $this->form_validation->run('carts')*/):
			if($this->getEM()->getRepository('Entity\ShCart')->addCarts($this->input)):
				$this->log(7,array($this->data['user']));
				$this->session->set_flashdata('success','Thêm Giỏ Hàng Thành Công');
			redirect('/admin/carts');
			else:
				$this->data['flash'] = array('error'=>'Lỗi sql, Thử lại');
			endif;
		endif;
		return true;
	}
}
?>